package cn.wen.base.view.limit;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;

import cn.wen.base.R;


/**
 * 可以单独或者和ViewPager结合使用的View
 *
 * @author 刘付文
 */

public class TabLayoutView extends HorizontalScrollView implements ViewPager.OnPageChangeListener {
    /**
     * 一屏幕显示的TAB个数
     */
    private int mTabCount = 0;

    private TabContainerView mTabContainer;

    private TabAdapter mAdapter;
    private int mItemWidth;
    private ViewPager mViewPager;

    /**
     * 当前位置
     */
    private int mCurrentPosition = 0;
    /**
     * 解决抖动的问题
     */
    private boolean isScroll;
    /**
     * 点击Item的时候是否滚动ViewPager
     */
    private boolean smoothScroll = false;

    public TabLayoutView(Context context) {
        this(context, null);
    }

    public TabLayoutView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TabLayoutView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.TabLayoutView);
        mTabCount = array.getInt(R.styleable.TabLayoutView_tabCount, mTabCount);
        array.recycle();
        mTabContainer = new TabContainerView(context);
        addView(mTabContainer);
    }

    public void setAdapter(TabAdapter adapter) {
        if (adapter == null) {
            throw new NullPointerException("TabAdapter is null");
        }
        mAdapter = adapter;
        int count = mAdapter.getCount();
        mTabContainer.removeAllItemViews();
        for (int i = 0; i < count; i++) {
            View itemView = mAdapter.getView(i, mTabContainer);
            mTabContainer.addItemView(itemView);
            if (mViewPager != null) {
                // 与ViewPager联动
                switchItemClick(itemView, i);
            } else {
                setItemClick(itemView, i);
            }
        }
        // 默认选中第一个位置
        mAdapter.onTabSelected(mTabContainer.getItemAt(mCurrentPosition), mCurrentPosition);
    }

    private void setItemClick(View itemView, final int position) {
        itemView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setItemSelected(position);
            }
        });
    }

    /**
     * 与ViewPager联动
     */
    private void switchItemClick(View mItemView, final int position) {
        mItemView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mViewPager.setCurrentItem(position, smoothScroll);
                // 用户ItemView点击时，不断滚动到当前的位置
                smoothScrollTab(position);
                // 用户点击时，滚动底部的指示器
                scrollBottomLine(position);
            }
        });
    }

    /**
     * 用户点击时，不断滚动到当前的位置
     */
    private void smoothScrollTab(int position) {
        // 总的滚动距离
        float totalScroll = (position) * mItemWidth;
        // 左边的偏移
        float offsetScroll = (getWidth() - mItemWidth) / 2;
        // 最终要滚的距离
        float finalScroll = totalScroll - offsetScroll;
        smoothScrollTo((int) finalScroll, 0);
    }

    /**
     * 用户点击时，滚动底部的指示器
     */
    private void scrollBottomLine(int position) {
        mTabContainer.scrollBottomLine(position);
    }

    /**
     * 关联ViewPager
     *
     * @param adapter
     * @param viewPager
     */
    public void setAdapter(TabAdapter adapter, ViewPager viewPager) {
        if (viewPager == null) {
            throw new NullPointerException("viewPager is null");
        }
        this.mViewPager = viewPager;
        setAdapter(adapter);

        mViewPager.addOnPageChangeListener(this);

    }


    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (changed) {
            // 单个Item的宽度
            mItemWidth = getItemWidth();
            for (int i = 0; i < mAdapter.getCount(); i++) {
                ViewGroup.LayoutParams layoutParams = mTabContainer.getItemAt(i).getLayoutParams();
                layoutParams.width = mItemWidth;
                mTabContainer.getItemAt(i).setLayoutParams(layoutParams);
            }
            // 如果没有指定个数，就取最宽的
            // 如果所有宽度不够一屏，就显示成一屏
            // 添加底部的指示器
            mTabContainer.addTabBottomLineView(mAdapter.getTabBottomLineView(), mItemWidth);

        }
    }

    public int getItemWidth() {
        // 整个布局的宽度
        int width = getWidth();
        // 如果指定了
        if (mTabCount > 0) {
            return width / mTabCount;
        }
        // 没有指定
        int itemWidth;
        // 取最宽的
        int maxWidth = 0;

        for (int i = 0; i < mAdapter.getCount(); i++) {
            int currentWidth = mTabContainer.getItemAt(i).getWidth();
            // 取条目最大的宽度
            maxWidth = Math.max(currentWidth, maxWidth);
        }
        itemWidth = maxWidth;
        // 如果所有宽度不够一屏
        if (maxWidth * mAdapter.getCount() < width) {
            itemWidth = width / mAdapter.getCount();
        }
        return itemWidth;
    }


    /**
     * 滚动底部的指示器
     */
    private void scrollBottomLine(int position, float positionOffset) {
        mTabContainer.scrollBottomLine(position, positionOffset);
    }

    /**
     * 划动时，不断滚动当前的位置
     */
    private void scrollTab(int position, float positionOffset) {
        // 总的滚动距离
        float totalScroll = (position + positionOffset) * mItemWidth;
        // 左边的偏移
        float offsetScroll = (getWidth() - mItemWidth) / 2;
        // 最终要滚的距离
        float finalScroll = totalScroll - offsetScroll;
        scrollTo((int) finalScroll, 0);
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        // 划动ViewPager就执行，用户点击ItemView不执行
        if (isScroll) {
            // 不断滚动当前的指示器
            scrollTab(position, positionOffset);
            // 滚动底部的指示器
            scrollBottomLine(position, positionOffset);
        }
    }

    @Override
    public void onPageSelected(int position) {
        setItemSelected(position);

    }

    /**
     * 设置Item选中
     */
    private void setItemSelected(int position) {
        if (mCurrentPosition != position) {
            // 重置上一个位置
            mAdapter.onTabReset(mTabContainer.getItemAt(mCurrentPosition), mCurrentPosition);
            mCurrentPosition = position;
            // 选中当前位置
            mAdapter.onTabSelected(mTabContainer.getItemAt(mCurrentPosition), mCurrentPosition);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        // 用户点击ItemView状态不会有 1
        //isScroll=state==1;
        // 点击：2--->0
        // 划动：1-->2-->0
        if (state == 1) {
            isScroll = true;
        }
        if (state == 0) {
            isScroll = false;
        }
    }

    /**
     * 点击Item的时候是否滚动ViewPager
     *
     * @param smoothScroll 切换Item时设置是否滚动
     */
    public void setViewPagerSmoothScroll(boolean smoothScroll) {
        this.smoothScroll = smoothScroll;
    }
}
